package com.progroup.kyrsmoney.parsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.FloatMath;
import android.util.Log;

import com.progroup.checks.Checks;
import com.progroup.kyrsmoney.database.DBAdapter;

public class ParseXml {
	
	private Context context;
	private String[] usd_buy, usd_sale;
	private String[] eur_buy, eur_sale;
	private String[] rub_buy, rub_sale;
	private String[] name_bank_eur,name_bank_usd,name_bank_rub;
	private int[] ID;
	int e = 0;
	public ParseXml(Context con){
		this.context =con;
	}
	
	public void Parsing(int[] ID){
		
		if(Checks.getDayOfWeek()!=7&Checks.getDayOfWeek()!=1){
			if(Checks.isIdToday(context)){
				setUpdate();
			}else{
				setParsing(ID);
			}
		}
		
		
	}
	
	
	
	

	
  
	
	public void setParsing(int[] ID){
		
		DBAdapter db = new DBAdapter(context);
		db.open();
		String date =Checks.getTodayDatenotSymbol();
		for(int i = 0; i<ID.length; i++){
			
			db.DB_ADD_KYRS(ID[i], "0", "0", "0", "0", "0", "0", date);
		}
		db.close();
		
		try{
			getParseEUR(getGetEur());
			getParseUSD(getGetUsd());
			getParseRUB(getGetRub());
			
			for(int r = 0; r<name_bank_eur.length; r++){
				int id = getId(name_bank_eur[r]);
				db.open();
				db.DB_UPDATE_KYRS_EUR(id,eur_buy[r], eur_sale[r], date);
				db.close();
			}
			
			for(int r = 0; r<name_bank_usd.length; r++){
				int id = getId(name_bank_usd[r]);
				db.open();
				db.DB_UPDATE_KYRS_USD(id, usd_buy[r], usd_sale[r], date);
				db.close();
			}
			
			for(int r = 0; r<name_bank_rub.length; r++){
				int id = getId(name_bank_rub[r]);
				db.open();
				db.DB_UPDATE_KYRS_RUB(id,rub_buy[r], rub_sale[r], date);
				db.close();
			}
			
		}catch (SQLException e) {
			// TODO: handle exception
		}catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	
	
	
	public void setUpdate(){
		
		DBAdapter db = new DBAdapter(context);
		String date = Checks.getTodayDatenotSymbol();
		getParseEUR(getGetEur());
		getParseUSD(getGetUsd());
		getParseRUB(getGetRub());
		try{
			for(int r = 0; r<name_bank_eur.length; r++){
				int id = getId(name_bank_eur[r]);
				db.open();
				db.DB_UPDATE_KYRS_EUR(id,eur_buy[r], eur_sale[r], date);
				db.close();
			}
			
			for(int r = 0; r<name_bank_usd.length; r++){
				int id = getId(name_bank_usd[r]);
				db.open();
				db.DB_UPDATE_KYRS_USD(id, usd_buy[r], usd_sale[r], date);
				db.close();
			}
			
			for(int r = 0; r<name_bank_rub.length; r++){
				int id = getId(name_bank_rub[r]);
				db.open();
				db.DB_UPDATE_KYRS_RUB(id,rub_buy[r], rub_sale[r], date);
				db.close();
			}
		}catch (SQLException e) {
			// TODO: handle exception
		}catch (Exception e) {
			// TODO: handle exception
		}
		
		
		
	}
	
	
	
	
	
	public int getId(String NAME){
		int id = 0;
		//Log.i("GETIDDDDD", NAME);
		DBAdapter db = new DBAdapter(context);
		db.open();
		Cursor cursor = db.SQL("SELECT _id FROM tblBankInfo WHERE name='"+NAME+"'");
		cursor.moveToFirst();
		id = cursor.getInt(0);
		cursor.close();
		db.close();
		//Log.i("GETIDDDDD", id+"");
		return id;
	}
	
	
	
	public String getGetEur(){
		HttpEntity entity= null;
		String entityContents = null;
		InputStream is = null;
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet("http://sravnibank.com.ua/kursy-valut/cash_xml/?id=exchangeratei-281114&currency=eur");
			HttpResponse response;
			
			response = httpclient.execute(httpget);
			
			entity = response.getEntity();
			
			
			
			is = entity.getContent() ;
			
			
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is,  "windows-1251"));
				
				StringBuilder sb = new StringBuilder();
				String line = null;                     
				
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
					
				}
				is.close();
				entityContents = sb.toString();
			} catch (Exception e) {
				Log.e("getJSONfromURLlog_tag222", "Error converting result " + e.toString());
			}
			
			
			//Log.i("getJSONfromURLlog_tagEURO", entityContents);
			
			
			
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		
		return entityContents;
	}
	

	public String getGetUsd(){
		HttpEntity entity= null;
		String entityContents = null;
		InputStream is = null;
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet("http://sravnibank.com.ua/kursy-valut/cash_xml/?id=exchangeratei-281114&currency=usd");
			HttpResponse response;
			
			response = httpclient.execute(httpget);
			
			entity = response.getEntity();
			
			
			
			is = entity.getContent() ;
			
			
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is,  "windows-1251"));
				
				StringBuilder sb = new StringBuilder();
				String line = null;                     
				
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
					
				}
				is.close();
				entityContents = sb.toString();
			} catch (Exception e) {
				Log.e("getJSONfromURLlog_tag222", "Error converting result " + e.toString());
			}
			
			
			//Log.i("getJSONfromURLlog_tagUSD", entityContents);
			
			
			
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		
		return entityContents;
	}
	public String getGetRub(){
		HttpEntity entity= null;
		String entityContents = null;
		InputStream is = null;
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet("http://sravnibank.com.ua/kursy-valut/cash_xml/?id=exchangeratei-281114&currency=rub");
			HttpResponse response;
			
			response = httpclient.execute(httpget);
			
			entity = response.getEntity();
			
			
			
			is = entity.getContent() ;
			
			
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						is,  "windows-1251"));
				
				StringBuilder sb = new StringBuilder();
				String line = null;                     
				
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
					
				}
				is.close();
				entityContents = sb.toString();
			} catch (Exception e) {
				Log.e("getJSONfromURLlog_tag222", "Error converting result " + e.toString());
			}
			
			
			//Log.i("getJSONfromURLlog_tagUSD", entityContents);
			
			
			
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		
		return entityContents;
	}
	
	
	
	
	public void getParseEUR(String str_eur){
		 Document doc = getDomElement(str_eur);
	        NodeList nl = doc.getElementsByTagName("Bank");
	        int length = nl.getLength();
	        eur_buy = new String [length];
		    eur_sale = new String [length];
		    name_bank_eur = new String [length];
	        for(int i=0;  i < length; i++)
	         {
	          Element e = (Element) nl.item(i);
	          
	          name_bank_eur[i]= getTagValue("Name", e);
	          eur_buy[i]= AddNull(getTagValue("Buy", e), 0);
	          eur_sale[i]= AddNull(getTagValue("Sale", e), 0);
	         
	          
	          
	         }
	        
	}
	public void getParseUSD(String str_usd){
		 Document doc = getDomElement(str_usd);
	        NodeList nl = doc.getElementsByTagName("Bank");
	        int length = nl.getLength();
	       usd_buy = new String [length];
	       usd_sale = new String [length];
	       name_bank_usd = new String [length];
	        for(int i=0;  i < length; i++)
	         {
	          Element e = (Element) nl.item(i);
	          
	          name_bank_usd[i]= getTagValue("Name", e);
	          usd_buy[i]= AddNull(getTagValue("Buy", e), 0);
	          usd_sale[i]= AddNull(getTagValue("Sale", e), 0);
	          
	         }
	      
	}
	
	public void getParseRUB(String str_rub){
		 Document doc = getDomElement(str_rub);
	        NodeList nl = doc.getElementsByTagName("Bank");
	        int length = nl.getLength();
	       rub_buy = new String [length];
	       rub_sale = new String [length];
	       name_bank_rub = new String [length];
	        for(int i=0;  i < length; i++)
	         {
	          Element e = (Element) nl.item(i);
	          
	          name_bank_rub[i]= getTagValue("Name", e);
	          rub_buy[i]= AddNull(getTagValue("Buy", e), 1);
	          rub_sale[i]= AddNull(getTagValue("Sale", e), 1);

	         }
	      
	}
	
	
	public Document getDomElement(String xml){
		
	      Document doc = null;
	      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	      try {
	    	  
	          DocumentBuilder db = dbf.newDocumentBuilder();

	          InputSource is = new InputSource();
	              is.setCharacterStream(new StringReader(xml));
	              doc = db.parse(is); 

	          } catch (ParserConfigurationException e) {
	              Log.e("Error: ", e.getMessage());
	              return null;
	          } catch (SAXException e) {
	              Log.e("Error: ", e.getMessage());
	              return null;
	          } catch (IOException e) {
	              Log.e("Error: ", e.getMessage());
	              return null;
	          }
	     // Log.i("GETDOMELEMENT", ""+doc.toString());
	          return doc;
	  }
	  
	  
	  public String getValue(Element item, String str) {
		    NodeList n = item.getElementsByTagName(str);
		   // Log.i("GETVALUE", ""+this.getElementValue(n.item(0)));
		    return this.getElementValue(n.item(0));
		}
	  
	  public String getTagValue(String sTag, Element eElement) {
			NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

		      Node nValue = (Node) nlList.item(0);
		    //  Log.i("GETTAGVALUE", ""+nValue.getNodeValue());
			return nValue.getNodeValue();
		}
	  
		 
		public final String getElementValue( Node elem ) {
		         Node child;
		         if( elem != null){
		             if (elem.hasChildNodes()){
		                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
		                     if( child.getNodeType() == Node.TEXT_NODE  ){
		                    	// Log.i("GETELEMENTVALUE", ""+child.getNodeValue());
		                         return child.getNodeValue();
		                     }
		                 }
		             }
		         }
		         return "";
		  }    
		
		public boolean FloatString(String str){
			String [] s = str.split("\\.");
			if(s[0].equalsIgnoreCase("0")){
				return true;
			}else{
				return false;
			}
		}
		
		
		
		public static String AddNull(String s, int parametr){
			
			DecimalFormat dm =null;
			if(parametr==0){
					dm=new DecimalFormat("##.000");
			}else{
				dm=new DecimalFormat("0.000");
			}
			DecimalFormatSymbols symbol = new DecimalFormatSymbols();
			symbol.setDecimalSeparator('.');
			dm.setDecimalFormatSymbols(symbol);

			return dm.format(Double.parseDouble(s));
			
		}
	
}